package com.compomics.multidentparser.crux;

import com.compomics.multidentparser.model.Content;
import com.compomics.multidentparser.model.SearchEngineHit;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * This class holds the parser engine for the Crux algorithm (with Percolator support).
 * 
 * @author Thilo Muth
 *
 */
public class CruxParser {
	
	/**
	 * This method reads the content of the Crux output file.
	 * @param filename Crux output filename.
	 * @return The content of the parsed Crux output file.
	 */
	public static Content read(String filename) {

		// Initialize the reader.
		BufferedReader reader = null;

		// Init the search engine hits.
		List<SearchEngineHit> searchEngineHits = null;

		try {
			reader = new BufferedReader(new FileReader(filename));
			String nextLine;
			searchEngineHits = new ArrayList<SearchEngineHit>();
			// Iterate over all the lines of the file.
			while ((nextLine = reader.readLine()) != null) {

				if (!nextLine.startsWith("scan")) {
					StringTokenizer tokenizer = new StringTokenizer(nextLine, "\t");
					List<String> tokenList = new ArrayList<String>();
					CruxHit hit = new CruxHit();

					// Iterate over all the tokens
					while (tokenizer.hasMoreTokens()) {
						tokenList.add(tokenizer.nextToken());
					}

					// Check tokenList for null
					if (tokenList.size() > 0) {
						hit.setScanNumber(Integer.valueOf(tokenList.get(0)));
						hit.setCharge(Integer.valueOf(tokenList.get(1)));
						hit.setPrecursorMz(Double.valueOf(tokenList.get(2)));
						hit.setNeutralMass(Double.valueOf(tokenList.get(3)));
						hit.setPeptideMass(Double.valueOf(tokenList.get(4)));
						hit.setDeltaCn(Double.valueOf(tokenList.get(5)));
						hit.setXCorrScore(Double.valueOf(tokenList.get(6)));
						hit.setXCorrRank(Integer.valueOf(tokenList.get(7)));
						hit.setPercolatorScore(Double.valueOf(tokenList.get(8)));
						hit.setPercolatorRank(Integer.valueOf(tokenList.get(9)));
						hit.setQValue(Double.valueOf(tokenList.get(10)));
						hit.setPepValue(Double.valueOf(tokenList.get(11)));
						hit.setMatchesSpectrum(Integer.valueOf(tokenList.get(12)));
						hit.setPeptideSequence(tokenList.get(13));
						hit.setCleavageType(tokenList.get(14));
						hit.setProteinids(tokenList.get(15));
						hit.setFlankingAA(tokenList.get(16));
						searchEngineHits.add(hit);
					}
				}
			}
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new Content(searchEngineHits, filename);
	}
}
